package http

import (
	"gitee.com/legend9999/publisher/dao"
	"net/http"
	"net/url"
	"strconv"
)

type Page struct {
	*dao.Page
	URL string // 分页的url
}

func NewPageFromR(r *http.Request) *Page {
	var daoPage = new(dao.Page)
	daoPage.PageNum, _ = strconv.Atoi(r.FormValue("pageNum"))
	daoPage.PageSize, _ = strconv.Atoi(r.FormValue("pageSize"))

	if daoPage.PageNum == 0 {
		daoPage.PageNum = 1
	}
	if daoPage.PageSize == 0 {
		daoPage.PageSize = 100
	}
	p := &Page{}
	p.Page = daoPage
	p.URL = PageLink(r)
	return p
}
func (p *Page) PageRange() []int {
	var result []int
	for i := 1; i < p.PageCount()+1; i++ {
		result = append(result, i)
	}
	return result
}

// PageCount 总页数
func (p *Page) PageCount() int {
	mod := p.RecordCount % p.PageSize
	if mod == 0 {
		return p.RecordCount / p.PageSize
	}
	return p.RecordCount/p.PageSize + 1
}

func (p *Page) PageLink(pageNum int) string {
	link, _ := url.ParseRequestURI(p.URL)
	values := link.Query()
	values.Set("pageNum", strconv.Itoa(pageNum))
	link.RawQuery = values.Encode()
	return link.String()
}

// PageLink 分页链接
func PageLink(r *http.Request) string {
	link, _ := url.ParseRequestURI(r.RequestURI)
	values := link.Query()
	values.Del("pageNum")
	link.RawQuery = values.Encode()
	return link.String()
}
